<script lang="ts" setup>
import InputVant from "@/components/HYInut/input.vue";
import disableImg from "@/image/new_img/btnv2_reg_disable.png";
import enableImg from "@/image/new_img/btnv2_reg_enable.png";
import LoginPwd from "@/image/new_img/login_pwd.svg";
import QuxiaoyulanBai from "@/image/new_img/quxiaoyulan_bai.png";
import { useRouter } from "vue-router";
import DeviceDetector from "device-detector-js";
import { ref, onMounted, reactive, watch } from "vue";
import { UserAxios } from "@/api";
import { UserStore } from "@/store";
import sortBy from "lodash";
import Pubsub from "pubsub-js";
import { PubSubEnum } from "@/types";
import { useI18n } from "vue-i18n";
import CryptoJS from "crypto-js";
import { FiltrationFun } from "@/utils";
const { t } = useI18n();
const logonType = ref(0);
//获取当前用户信息
const userStore = UserStore();
const router = useRouter();
const getUserNameRef = ref();
const getPassword = ref();
const getPassword2 = ref();
const updata = reactive({
  username: "",
  passwd: "",
  email: "",
  uniqid: localStorage.getItem("deviceUniqueKey") || "",
  device: "",
  deviceId: "",
  upper_id: 0,
  linkId: "", //绑定下级的
  advid: "", //推广id
});

onMounted(async () => {
  const deviceDetector = new DeviceDetector();
  const { os } = deviceDetector.parse(navigator.userAgent);
  updata.device = os !== null ? os.name : "";
  // console.log("注册页面获取推广渠道ch", sessionStorage.getItem("advid"));
  // console.log("推荐人id", sessionStorage.getItem("linkId"));
});
//输入框的背景类型
const monitorType = ref(0);
const brazilNumberCheck = new RegExp(/^[0-9]{5,12}$/);
const passWordCheck = new RegExp(/^[0-9A-Za-z]{8,20}$/);
//获取用户名
const monitorInput = res => {
  if ((brazilNumberCheck.test(res) && res.length === 11) || res.length === 0) {
    monitorType.value = 0;
  } else {
    monitorType.value = 1;
  }
  updata.username = res;
  errType.value = 0;
};
//第一次密码的验证状态
const passwordCheckType = ref(0);
const definePasswordType = ref(0);
//第一次的密码
const setPassword = ref();
//判断是否可以注册
const provingConditionType = ref(false);
//密码校验
const monitorInputPassword = res => {
  if (passWordCheck.test(res) || res.length === 0) {
    passwordCheckType.value = 0;
    // if (passWordCheck.test(res)) {
    //   setPassword.value = res;
    // }
  } else {
    passwordCheckType.value = 1;
  }
  setPassword.value = res;
  if (updata.passwd.length !== 0) {
    if (updata.passwd === setPassword.value) {
      definePasswordType.value = 0;
    } else {
      definePasswordType.value = 2;
    }
  }
};
//确定密码
const monitorPassword = res => {
  if (res === setPassword.value && res.length !== 0) {
    definePasswordType.value = 0;
    updata.passwd = res;
  } else {
    updata.passwd = "";
    if (
      (res.length === setPassword.value.length && res !== setPassword.value) ||
      res.length > setPassword.value.length
    ) {
      definePasswordType.value = 2;
    } else {
      definePasswordType.value = 1;
    }
  }
};
//监听参数，用户名，密码，重置密码
watch(
  [setPassword, () => updata.passwd, () => updata.username],
  newValue => {
    if (
      brazilNumberCheck.test(newValue[2]) &&
      newValue[2].length === 11 &&
      passWordCheck.test(newValue[1]) &&
      passWordCheck.test(newValue[0]) &&
      newValue[1] === newValue[0]
    ) {
      provingConditionType.value = true;
    } else {
      provingConditionType.value = false;
    }
  },
  { deep: true },
);
const errInputPasswd = ref("");
//失败的提示1：账号重复 2：ip受限
const errType = ref(0);
//注册后登录
const gotopage = sortBy.throttle(() => {
  if (provingConditionType.value === false) {
    return false;
  }
  Pubsub.publish(PubSubEnum.SHOW_LOADING);
  //这个是分享的
  const linkId = sessionStorage.getItem("linkId");
  if (linkId && linkId !== "" && linkId !== null) {
    updata.linkId = linkId;
  }
  const advid = sessionStorage.getItem("advid");
  //这个是推广的
  if (advid !== null && advid !== "" && advid) {
    updata.advid = advid;
  }
  errInputPasswd.value = updata.passwd;
  updata.passwd = CryptoJS.MD5(updata.passwd).toString();
  UserAxios.register(updata)
    .then(_res => {
      //登录
      if (!_res) {
        return;
      }
      //注册的事件回传
      FiltrationFun.setReportEvent("CompleteRegistration");
      UserAxios.login({
        username: updata.username,
        passwd: updata.passwd,
        device: updata.device,
        deviceId: updata.deviceId,
      }).then(res => {
        //登陆的事件回传
        FiltrationFun.setReportEvent("SubmitApplication");
        userStore.setUserLoginInfo(res);
        //获取用户信息
        Pubsub.publish(PubSubEnum.UPDATE_USERINFO);
        Pubsub.publish(PubSubEnum.HIDE_LOADING);
        router.back();
      });
    })
    .catch(e => {
      provingConditionType.value = true;
      updata.passwd = errInputPasswd.value;
      if (e.code === 2003) {
        errType.value = 1;
      }
      if (e.code === 1103) {
        errType.value = 2;
      }
    })
    .finally(() => {
      Pubsub.publish(PubSubEnum.HIDE_LOADING);
    });
}, 2000);
</script>
<template>
  <div class="input-content">
    <InputVant
      ref="getUserNameRef"
      :placeholder="t('inputPlaceholder.registroAccount')"
      country-type="1"
      :monitor-type="monitorType"
      input-type="number"
      @monitor-input="monitorInput"
    >
      <template #errorMessage>
        <div v-show="monitorType == 1" class="signup-item-error">
          {{ t("login.correctAccountNumber") }}
        </div>
        <div v-show="errType == 1" class="signup-item-error">
          {{ t("login.err2003") }}
        </div>
        <div v-show="errType == 2" class="signup-item-error">
          {{ t("responseTip.ipRestrict") }}
        </div>
      </template>
    </InputVant>
    <InputVant
      ref="getPassword"
      :placeholder="t('inputPlaceholder.loginPassword')"
      class="input-segment-frame"
      :monitor-type="passwordCheckType"
      :letf-icon="LoginPwd"
      :rigth-icon="QuxiaoyulanBai"
      :input-type="'password'"
      @monitor-input="monitorInputPassword"
    >
      <template #errorMessage>
        <div v-show="passwordCheckType == 1" class="signup-item-error">
          {{ t("login.correctPassword") }}
        </div>
      </template>
    </InputVant>
    <InputVant
      ref="getPassword2"
      :placeholder="t('inputPlaceholder.registroConfirmPassword')"
      class="input-segment-frame"
      :monitor-type="definePasswordType"
      :input-type="'password'"
      :letf-icon="LoginPwd"
      :rigth-icon="QuxiaoyulanBai"
      @monitor-input="monitorPassword"
    >
      <template #errorMessage>
        <div v-show="definePasswordType !== 0" class="signup-item-error">
          <div v-show="definePasswordType === 1">{{ t("login.correctPassword") }}</div>
          <div v-show="definePasswordType === 2">{{ t("login.differentPasswords") }}</div>
        </div>
      </template>
    </InputVant>
    <div
      class="bottom-frame df ai-center jc-center"
      :class="{ 'text-select': logonType != 1 }"
      :style="{ backgroundImage: `url(${!provingConditionType ? disableImg : enableImg})` }"
      @click="gotopage"
    ></div>
  </div>
</template>
<style lang="less" scoped>
.input-segment-frame {
  margin-top: 18.0781px;
}

.bottom-frame {
  width: 250px;
  height: 100px;
  margin: auto;
  font-size: 32px;
  color: rgba(255, 255, 255, 0.45);
  background-size: cover;
  background-repeat: round;
  margin-top: 46px;
}

.signup-item-error {
  font-size: 28px;
  color: #eb5757;
  padding-left: 40px;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  padding-top: 20px;
  line-height: 40px;
  margin-bottom: 20px;
}
</style>
